//
//  AddressBookController.swift
//  AddressBook
//
//  Created by admin on 16/1/20.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit
// 遵循了两个自定的代理协议
class AddressBookController: UITableViewController,AddAddressControllerDelegate,EditAddressControllerDelegate {
    @IBOutlet weak var titleView: UINavigationItem!
    // 联系人数据数组
    var addreses:[Address]! = Address.readeAddresses()
        {
            didSet
            {
                Address.writeAddresses(addreses)
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    // 登出
    @IBAction func logout(sender: UIBarButtonItem) {
        let userInfo = NSDictionary(contentsOfFile: userInfoPath)
//        userInfo.setValue("", forKey: "userName")
        userInfo!.setValue("", forKey: "password")
        userInfo!.writeToFile(userInfoPath, atomically: true)
        self.navigationController?.popToRootViewControllerAnimated(true)
    }
    // 删除按钮点击之后，改变编辑状态
    @IBAction func deleteAddress(sender: UIBarButtonItem) {
        self.tableView.editing = !self.tableView.editing
    }
    // 根据编辑状态做相应操作
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        switch editingStyle
        {
        case UITableViewCellEditingStyle.Delete :
            self.addreses.removeAtIndex(indexPath.row)
            self.tableView.deleteRowsAtIndexPaths([NSIndexPath(forRow: indexPath.row, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Fade)
            break
        default :
            break
        }
    }
    // 跳转时判断，不同的控制器做不同的操作
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        super.prepareForSegue(segue, sender: nil)
        if segue.destinationViewController is LoginController// 返回登录控制器直接返回
        {
            segue.destinationViewController.viewDidLoad()
        }
        else if segue.destinationViewController is AddAddressController// 添加控制器则设置代理
        {
            (segue.destinationViewController as! AddAddressController).addAddressDelegate = self
        }
        else if segue.destinationViewController is EditAddressController// 编辑控制器则设置代理以及传递当前选择的address模型
        {
            let dest = segue.destinationViewController as! EditAddressController
            dest.address = self.addreses[(tableView.indexPathForSelectedRow?.row)!]
            dest.editAddressDelegate = self
        }
    }
    // 执行保存数据代理方法
    func saveAddressButtonClicked(address: Address) {
        self.addreses.append(address)
        // 插入新行数据
        self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.addreses.count - 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Fade)
    }
    // 编辑address代理方法，用以刷新数据之后改变cell为最新内容
    func ediitAddressSaveButonClicked(address:Address) {
        let index = self.addreses.indexOf(address)// 找到当前改变的addree的下标
        self.addreses[index!] = address // 覆盖值
        self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: index!, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Fade) // 刷新cell
//        print(index)
    }
    // MARK: - Table view data source
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.addreses.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let identifer = "addressCell"
        // 从缓冲池中获取cell
        var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(identifer)
        // 当没有获取到cell的时候，实例化新的cell
        cell = (cell == nil) ? UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: identifer) : cell
        cell.textLabel?.text = self.addreses[indexPath.row].name as String
        cell.detailTextLabel?.text = self.addreses[indexPath.row].address as String
        return cell
    }
    // 点击cell执行方法
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.performSegueWithIdentifier("EditAddress", sender: nil)
    }
    // 设置cell编辑状态的style
    override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
        return UITableViewCellEditingStyle.Delete
    }
}
